//! 指标收集模块

use crate::Result;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use parking_lot::RwLock;
use std::collections::HashMap;

/// 数据库指标收集器
#[derive(Debug)]
pub struct MetricsCollector {
    /// 查询指标
    query_metrics: Arc<QueryMetrics>,
    /// 存储指标
    storage_metrics: Arc<StorageMetrics>,
    /// 网络指标
    network_metrics: Arc<NetworkMetrics>,
    /// 系统指标
    system_metrics: Arc<SystemMetrics>,
    /// 自定义指标
    custom_metrics: Arc<RwLock<HashMap<String, CustomMetric>>>,
    /// 性能调优器
    performance_tuner: Arc<RwLock<PerformanceTuner>>,
}

/// 性能调优器
#[derive(Debug)]
pub struct PerformanceTuner {
    /// 调优配置
    config: TuningConfig,
    /// 性能历史记录
    performance_history: Vec<PerformanceSnapshot>,
    /// 调优建议
    recommendations: Vec<TuningRecommendation>,
}

/// 调优配置
#[derive(Debug, Clone)]
pub struct TuningConfig {
    /// 是否启用自动调优
    pub auto_tuning_enabled: bool,
    /// 监控间隔（秒）
    pub monitoring_interval: u64,
    /// 历史记录保留数量
    pub history_retention_count: usize,
    /// 性能阈值
    pub performance_thresholds: PerformanceThresholds,
}

/// 性能阈值
#[derive(Debug, Clone)]
pub struct PerformanceThresholds {
    /// 最大查询时间（毫秒）
    pub max_query_time_ms: u64,
    /// 最大内存使用率
    pub max_memory_usage_percent: f64,
    /// 最大CPU使用率
    pub max_cpu_usage_percent: f64,
    /// 最小缓存命中率
    pub min_cache_hit_rate: f64,
}

/// 性能快照
#[derive(Debug, Clone)]
pub struct PerformanceSnapshot {
    /// 时间戳
    pub timestamp: std::time::SystemTime,
    /// 查询性能
    pub query_performance: QueryPerformance,
    /// 内存使用情况
    pub memory_usage: MemoryUsage,
    /// CPU使用情况
    pub cpu_usage: f64,
    /// 缓存性能
    pub cache_performance: CachePerformance,
}

/// 查询性能
#[derive(Debug, Clone)]
pub struct QueryPerformance {
    /// 平均查询时间（毫秒）
    pub avg_query_time_ms: f64,
    /// 最大查询时间（毫秒）
    pub max_query_time_ms: u64,
    /// 查询吞吐量（QPS）
    pub queries_per_second: f64,
    /// 慢查询数量
    pub slow_queries_count: u64,
}

/// 内存使用情况
#[derive(Debug, Clone)]
pub struct MemoryUsage {
    /// 总内存（字节）
    pub total_memory_bytes: u64,
    /// 已使用内存（字节）
    pub used_memory_bytes: u64,
    /// 内存使用率
    pub usage_percent: f64,
}

/// 缓存性能
#[derive(Debug, Clone)]
pub struct CachePerformance {
    /// 缓存命中次数
    pub cache_hits: u64,
    /// 缓存未命中次数
    pub cache_misses: u64,
    /// 缓存命中率
    pub hit_rate: f64,
}

/// 调优建议
#[derive(Debug, Clone)]
pub struct TuningRecommendation {
    /// 建议类型
    pub recommendation_type: RecommendationType,
    /// 建议描述
    pub description: String,
    /// 优先级
    pub priority: Priority,
    /// 预期影响
    pub expected_impact: String,
}

/// 建议类型
#[derive(Debug, Clone)]
pub enum RecommendationType {
    /// 内存优化
    MemoryOptimization,
    /// 查询优化
    QueryOptimization,
    /// 索引优化
    IndexOptimization,
    /// 缓存优化
    CacheOptimization,
    /// 配置调整
    ConfigurationTuning,
}

/// 优先级
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Priority {
    /// 低优先级
    Low,
    /// 中优先级
    Medium,
    /// 高优先级
    High,
    /// 紧急
    Critical,
}

impl MetricsCollector {
    /// 创建新的指标收集器
    pub fn new() -> Self {
        Self {
            query_metrics: Arc::new(QueryMetrics::new()),
            storage_metrics: Arc::new(StorageMetrics::new()),
            network_metrics: Arc::new(NetworkMetrics::new()),
            system_metrics: Arc::new(SystemMetrics::new()),
            custom_metrics: Arc::new(RwLock::new(HashMap::new())),
            performance_tuner: Arc::new(RwLock::new(PerformanceTuner::new())),
        }
    }

    /// 获取性能调优器
    pub fn get_performance_tuner(&self) -> Arc<RwLock<PerformanceTuner>> {
        self.performance_tuner.clone()
    }

    /// 收集性能快照
    pub fn collect_performance_snapshot(&self) -> PerformanceSnapshot {
        let query_metrics = self.query_metrics.get_summary();
        let storage_metrics = self.storage_metrics.get_summary();
        let system_metrics = self.system_metrics.get_summary();

        PerformanceSnapshot {
            timestamp: std::time::SystemTime::now(),
            query_performance: QueryPerformance {
                avg_query_time_ms: query_metrics.avg_execution_time_ms,
                max_query_time_ms: query_metrics.max_execution_time_ms,
                queries_per_second: query_metrics.queries_per_second,
                slow_queries_count: query_metrics.slow_queries,
            },
            memory_usage: MemoryUsage {
                total_memory_bytes: storage_metrics.total_memory_bytes,
                used_memory_bytes: storage_metrics.used_memory_bytes,
                usage_percent: (storage_metrics.used_memory_bytes as f64 / storage_metrics.total_memory_bytes as f64) * 100.0,
            },
            cpu_usage: system_metrics.cpu_usage_percent,
            cache_performance: CachePerformance {
                cache_hits: storage_metrics.cache_hits,
                cache_misses: storage_metrics.cache_misses,
                hit_rate: if storage_metrics.cache_hits + storage_metrics.cache_misses > 0 {
                    storage_metrics.cache_hits as f64 / (storage_metrics.cache_hits + storage_metrics.cache_misses) as f64
                } else {
                    0.0
                },
            },
        }
    }

    /// 执行性能分析
    pub fn analyze_performance(&self) -> Vec<TuningRecommendation> {
        let snapshot = self.collect_performance_snapshot();
        let mut tuner = self.performance_tuner.write();
        tuner.analyze_and_recommend(&snapshot)
    }
    
    /// 获取查询指标
    pub fn query_metrics(&self) -> Arc<QueryMetrics> {
        self.query_metrics.clone()
    }
    
    /// 获取存储指标
    pub fn storage_metrics(&self) -> Arc<StorageMetrics> {
        self.storage_metrics.clone()
    }
    
    /// 获取网络指标
    pub fn network_metrics(&self) -> Arc<NetworkMetrics> {
        self.network_metrics.clone()
    }
    
    /// 获取系统指标
    pub fn system_metrics(&self) -> Arc<SystemMetrics> {
        self.system_metrics.clone()
    }
    
    /// 添加自定义指标
    pub fn add_custom_metric(&self, name: String, metric: CustomMetric) {
        self.custom_metrics.write().insert(name, metric);
    }
    
    /// 获取所有指标快照
    pub fn get_snapshot(&self) -> MetricsSnapshot {
        MetricsSnapshot {
            query: self.query_metrics.get_snapshot(),
            storage: self.storage_metrics.get_snapshot(),
            network: self.network_metrics.get_snapshot(),
            system: self.system_metrics.get_snapshot(),
            custom: self.custom_metrics.read().clone(),
            timestamp: Instant::now(),
        }
    }
    
    /// 重置所有指标
    pub fn reset(&self) {
        self.query_metrics.reset();
        self.storage_metrics.reset();
        self.network_metrics.reset();
        self.system_metrics.reset();
        self.custom_metrics.write().clear();
    }
}

impl Default for MetricsCollector {
    fn default() -> Self {
        Self::new()
    }
}

/// 查询指标
#[derive(Debug)]
pub struct QueryMetrics {
    /// 查询总数
    total_queries: AtomicU64,
    /// 成功查询数
    successful_queries: AtomicU64,
    /// 失败查询数
    failed_queries: AtomicU64,
    /// 总查询时间（微秒）
    total_query_time_us: AtomicU64,
    /// 慢查询数
    slow_queries: AtomicU64,
    /// 当前活跃查询数
    active_queries: AtomicUsize,
}

impl QueryMetrics {
    /// 创建新的查询指标
    pub fn new() -> Self {
        Self {
            total_queries: AtomicU64::new(0),
            successful_queries: AtomicU64::new(0),
            failed_queries: AtomicU64::new(0),
            total_query_time_us: AtomicU64::new(0),
            slow_queries: AtomicU64::new(0),
            active_queries: AtomicUsize::new(0),
        }
    }
    
    /// 记录查询开始
    pub fn query_started(&self) -> QueryTimer {
        self.total_queries.fetch_add(1, Ordering::Relaxed);
        self.active_queries.fetch_add(1, Ordering::Relaxed);
        QueryTimer::new(self)
    }
    
    /// 记录查询完成
    pub fn query_completed(&self, duration: Duration, success: bool, is_slow: bool) {
        self.active_queries.fetch_sub(1, Ordering::Relaxed);
        self.total_query_time_us.fetch_add(duration.as_micros() as u64, Ordering::Relaxed);
        
        if success {
            self.successful_queries.fetch_add(1, Ordering::Relaxed);
        } else {
            self.failed_queries.fetch_add(1, Ordering::Relaxed);
        }
        
        if is_slow {
            self.slow_queries.fetch_add(1, Ordering::Relaxed);
        }
    }
    
    /// 获取指标快照
    pub fn get_snapshot(&self) -> QueryMetricsSnapshot {
        QueryMetricsSnapshot {
            total_queries: self.total_queries.load(Ordering::Relaxed),
            successful_queries: self.successful_queries.load(Ordering::Relaxed),
            failed_queries: self.failed_queries.load(Ordering::Relaxed),
            total_query_time_us: self.total_query_time_us.load(Ordering::Relaxed),
            slow_queries: self.slow_queries.load(Ordering::Relaxed),
            active_queries: self.active_queries.load(Ordering::Relaxed),
        }
    }
    
    /// 重置指标
    pub fn reset(&self) {
        self.total_queries.store(0, Ordering::Relaxed);
        self.successful_queries.store(0, Ordering::Relaxed);
        self.failed_queries.store(0, Ordering::Relaxed);
        self.total_query_time_us.store(0, Ordering::Relaxed);
        self.slow_queries.store(0, Ordering::Relaxed);
        // 不重置active_queries，因为可能有正在执行的查询
    }

    /// 获取查询指标摘要
    pub fn get_summary(&self) -> QueryMetricsSummary {
        let snapshot = self.get_snapshot();
        let avg_time_us = if snapshot.total_queries > 0 {
            snapshot.total_query_time_us as f64 / snapshot.total_queries as f64
        } else {
            0.0
        };

        QueryMetricsSummary {
            avg_execution_time_ms: avg_time_us / 1000.0,
            max_execution_time_ms: 0, // 简化实现
            queries_per_second: 0.0, // 简化实现
            slow_queries: snapshot.slow_queries,
        }
    }

    /// 记录查询执行
    pub fn record_query_execution(&self, duration: Duration) {
        let is_slow = duration.as_millis() > 1000; // 超过1秒认为是慢查询
        self.query_completed(duration, true, is_slow);
    }
}

/// 查询指标摘要
#[derive(Debug, Clone)]
pub struct QueryMetricsSummary {
    /// 平均执行时间（毫秒）
    pub avg_execution_time_ms: f64,
    /// 最大执行时间（毫秒）
    pub max_execution_time_ms: u64,
    /// 每秒查询数
    pub queries_per_second: f64,
    /// 慢查询数
    pub slow_queries: u64,
}

/// 查询计时器
pub struct QueryTimer {
    start_time: Instant,
    metrics: *const QueryMetrics,
}

impl QueryTimer {
    fn new(metrics: &QueryMetrics) -> Self {
        Self {
            start_time: Instant::now(),
            metrics: metrics as *const QueryMetrics,
        }
    }
    
    /// 完成查询计时
    pub fn finish(self, success: bool, slow_threshold: Duration) {
        let duration = self.start_time.elapsed();
        let is_slow = duration > slow_threshold;
        
        unsafe {
            (*self.metrics).query_completed(duration, success, is_slow);
        }
    }
}

/// 存储指标
#[derive(Debug)]
pub struct StorageMetrics {
    /// 读取操作数
    reads: AtomicU64,
    /// 写入操作数
    writes: AtomicU64,
    /// 读取字节数
    bytes_read: AtomicU64,
    /// 写入字节数
    bytes_written: AtomicU64,
    /// 缓存命中数
    cache_hits: AtomicU64,
    /// 缓存未命中数
    cache_misses: AtomicU64,
}

impl StorageMetrics {
    pub fn new() -> Self {
        Self {
            reads: AtomicU64::new(0),
            writes: AtomicU64::new(0),
            bytes_read: AtomicU64::new(0),
            bytes_written: AtomicU64::new(0),
            cache_hits: AtomicU64::new(0),
            cache_misses: AtomicU64::new(0),
        }
    }
    
    pub fn record_read(&self, bytes: u64) {
        self.reads.fetch_add(1, Ordering::Relaxed);
        self.bytes_read.fetch_add(bytes, Ordering::Relaxed);
    }
    
    pub fn record_write(&self, bytes: u64) {
        self.writes.fetch_add(1, Ordering::Relaxed);
        self.bytes_written.fetch_add(bytes, Ordering::Relaxed);
    }
    
    pub fn record_cache_hit(&self) {
        self.cache_hits.fetch_add(1, Ordering::Relaxed);
    }
    
    pub fn record_cache_miss(&self) {
        self.cache_misses.fetch_add(1, Ordering::Relaxed);
    }
    
    pub fn get_snapshot(&self) -> StorageMetricsSnapshot {
        StorageMetricsSnapshot {
            reads: self.reads.load(Ordering::Relaxed),
            writes: self.writes.load(Ordering::Relaxed),
            bytes_read: self.bytes_read.load(Ordering::Relaxed),
            bytes_written: self.bytes_written.load(Ordering::Relaxed),
            cache_hits: self.cache_hits.load(Ordering::Relaxed),
            cache_misses: self.cache_misses.load(Ordering::Relaxed),
        }
    }
    
    pub fn reset(&self) {
        self.reads.store(0, Ordering::Relaxed);
        self.writes.store(0, Ordering::Relaxed);
        self.bytes_read.store(0, Ordering::Relaxed);
        self.bytes_written.store(0, Ordering::Relaxed);
        self.cache_hits.store(0, Ordering::Relaxed);
        self.cache_misses.store(0, Ordering::Relaxed);
    }

    /// 获取存储指标摘要
    pub fn get_summary(&self) -> StorageMetricsSummary {
        let snapshot = self.get_snapshot();
        StorageMetricsSummary {
            total_memory_bytes: 1024 * 1024 * 1024, // 简化实现：1GB
            used_memory_bytes: snapshot.bytes_read + snapshot.bytes_written,
            cache_hits: snapshot.cache_hits,
            cache_misses: snapshot.cache_misses,
        }
    }
}

/// 存储指标摘要
#[derive(Debug, Clone)]
pub struct StorageMetricsSummary {
    /// 总内存（字节）
    pub total_memory_bytes: u64,
    /// 已使用内存（字节）
    pub used_memory_bytes: u64,
    /// 缓存命中数
    pub cache_hits: u64,
    /// 缓存未命中数
    pub cache_misses: u64,
}

/// 网络指标
#[derive(Debug)]
pub struct NetworkMetrics {
    /// 连接总数
    total_connections: AtomicU64,
    /// 当前活跃连接数
    active_connections: AtomicUsize,
    /// 接收字节数
    bytes_received: AtomicU64,
    /// 发送字节数
    bytes_sent: AtomicU64,
}

impl NetworkMetrics {
    pub fn new() -> Self {
        Self {
            total_connections: AtomicU64::new(0),
            active_connections: AtomicUsize::new(0),
            bytes_received: AtomicU64::new(0),
            bytes_sent: AtomicU64::new(0),
        }
    }
    
    pub fn connection_established(&self) {
        self.total_connections.fetch_add(1, Ordering::Relaxed);
        self.active_connections.fetch_add(1, Ordering::Relaxed);
    }
    
    pub fn connection_closed(&self) {
        self.active_connections.fetch_sub(1, Ordering::Relaxed);
    }
    
    pub fn record_bytes_received(&self, bytes: u64) {
        self.bytes_received.fetch_add(bytes, Ordering::Relaxed);
    }
    
    pub fn record_bytes_sent(&self, bytes: u64) {
        self.bytes_sent.fetch_add(bytes, Ordering::Relaxed);
    }
    
    pub fn get_snapshot(&self) -> NetworkMetricsSnapshot {
        NetworkMetricsSnapshot {
            total_connections: self.total_connections.load(Ordering::Relaxed),
            active_connections: self.active_connections.load(Ordering::Relaxed),
            bytes_received: self.bytes_received.load(Ordering::Relaxed),
            bytes_sent: self.bytes_sent.load(Ordering::Relaxed),
        }
    }
    
    pub fn reset(&self) {
        self.total_connections.store(0, Ordering::Relaxed);
        // 不重置active_connections
        self.bytes_received.store(0, Ordering::Relaxed);
        self.bytes_sent.store(0, Ordering::Relaxed);
    }
}

/// 系统指标
#[derive(Debug)]
pub struct SystemMetrics {
    /// 启动时间
    start_time: Instant,
    /// 内存使用量
    memory_usage: AtomicU64,
    /// CPU使用率（百分比 * 100）
    cpu_usage: AtomicU64,
}

impl SystemMetrics {
    pub fn new() -> Self {
        Self {
            start_time: Instant::now(),
            memory_usage: AtomicU64::new(0),
            cpu_usage: AtomicU64::new(0),
        }
    }
    
    pub fn update_memory_usage(&self, bytes: u64) {
        self.memory_usage.store(bytes, Ordering::Relaxed);
    }
    
    pub fn update_cpu_usage(&self, percentage: f64) {
        self.cpu_usage.store((percentage * 100.0) as u64, Ordering::Relaxed);
    }
    
    pub fn get_snapshot(&self) -> SystemMetricsSnapshot {
        SystemMetricsSnapshot {
            uptime: self.start_time.elapsed(),
            memory_usage: self.memory_usage.load(Ordering::Relaxed),
            cpu_usage: self.cpu_usage.load(Ordering::Relaxed) as f64 / 100.0,
        }
    }
    
    pub fn reset(&self) {
        // 不重置start_time和memory_usage
        self.cpu_usage.store(0, Ordering::Relaxed);
    }

    /// 获取系统指标摘要
    pub fn get_summary(&self) -> SystemMetricsSummary {
        let snapshot = self.get_snapshot();
        SystemMetricsSummary {
            cpu_usage_percent: snapshot.cpu_usage,
            memory_usage_bytes: snapshot.memory_usage,
            uptime_seconds: snapshot.uptime.as_secs(),
        }
    }
}

/// 系统指标摘要
#[derive(Debug, Clone)]
pub struct SystemMetricsSummary {
    /// CPU使用率（百分比）
    pub cpu_usage_percent: f64,
    /// 内存使用量（字节）
    pub memory_usage_bytes: u64,
    /// 运行时间（秒）
    pub uptime_seconds: u64,
}

/// 自定义指标
#[derive(Debug, Clone)]
pub enum CustomMetric {
    Counter(u64),
    Gauge(f64),
    Histogram(Vec<f64>),
}

/// 指标快照
#[derive(Debug, Clone)]
pub struct MetricsSnapshot {
    pub query: QueryMetricsSnapshot,
    pub storage: StorageMetricsSnapshot,
    pub network: NetworkMetricsSnapshot,
    pub system: SystemMetricsSnapshot,
    pub custom: HashMap<String, CustomMetric>,
    pub timestamp: Instant,
}

/// 查询指标快照
#[derive(Debug, Clone)]
pub struct QueryMetricsSnapshot {
    pub total_queries: u64,
    pub successful_queries: u64,
    pub failed_queries: u64,
    pub total_query_time_us: u64,
    pub slow_queries: u64,
    pub active_queries: usize,
}

impl QueryMetricsSnapshot {
    /// 计算平均查询时间（微秒）
    pub fn average_query_time_us(&self) -> f64 {
        if self.total_queries > 0 {
            self.total_query_time_us as f64 / self.total_queries as f64
        } else {
            0.0
        }
    }
    
    /// 计算成功率
    pub fn success_rate(&self) -> f64 {
        if self.total_queries > 0 {
            self.successful_queries as f64 / self.total_queries as f64
        } else {
            0.0
        }
    }
}

/// 存储指标快照
#[derive(Debug, Clone)]
pub struct StorageMetricsSnapshot {
    pub reads: u64,
    pub writes: u64,
    pub bytes_read: u64,
    pub bytes_written: u64,
    pub cache_hits: u64,
    pub cache_misses: u64,
}

impl StorageMetricsSnapshot {
    /// 计算缓存命中率
    pub fn cache_hit_rate(&self) -> f64 {
        let total_accesses = self.cache_hits + self.cache_misses;
        if total_accesses > 0 {
            self.cache_hits as f64 / total_accesses as f64
        } else {
            0.0
        }
    }
}

/// 网络指标快照
#[derive(Debug, Clone)]
pub struct NetworkMetricsSnapshot {
    pub total_connections: u64,
    pub active_connections: usize,
    pub bytes_received: u64,
    pub bytes_sent: u64,
}

/// 系统指标快照
#[derive(Debug, Clone)]
pub struct SystemMetricsSnapshot {
    pub uptime: Duration,
    pub memory_usage: u64,
    pub cpu_usage: f64,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;
    use std::time::Duration;
    
    #[test]
    fn test_metrics_collector_creation() {
        let collector = MetricsCollector::new();
        let snapshot = collector.get_snapshot();
        
        assert_eq!(snapshot.query.total_queries, 0);
        assert_eq!(snapshot.storage.reads, 0);
        assert_eq!(snapshot.network.total_connections, 0);
    }
    
    #[test]
    fn test_query_metrics() {
        let metrics = QueryMetrics::new();
        
        // 测试查询计时
        let timer = metrics.query_started();
        thread::sleep(Duration::from_millis(10));
        timer.finish(true, Duration::from_millis(100));
        
        let snapshot = metrics.get_snapshot();
        assert_eq!(snapshot.total_queries, 1);
        assert_eq!(snapshot.successful_queries, 1);
        assert_eq!(snapshot.failed_queries, 0);
        assert!(snapshot.total_query_time_us > 0);
    }
    
    #[test]
    fn test_storage_metrics() {
        let metrics = StorageMetrics::new();
        
        metrics.record_read(1024);
        metrics.record_write(512);
        metrics.record_cache_hit();
        metrics.record_cache_miss();
        
        let snapshot = metrics.get_snapshot();
        assert_eq!(snapshot.reads, 1);
        assert_eq!(snapshot.writes, 1);
        assert_eq!(snapshot.bytes_read, 1024);
        assert_eq!(snapshot.bytes_written, 512);
        assert_eq!(snapshot.cache_hits, 1);
        assert_eq!(snapshot.cache_misses, 1);
        assert_eq!(snapshot.cache_hit_rate(), 0.5);
    }
    
    #[test]
    fn test_network_metrics() {
        let metrics = NetworkMetrics::new();
        
        metrics.connection_established();
        metrics.record_bytes_received(1024);
        metrics.record_bytes_sent(512);
        
        let snapshot = metrics.get_snapshot();
        assert_eq!(snapshot.total_connections, 1);
        assert_eq!(snapshot.active_connections, 1);
        assert_eq!(snapshot.bytes_received, 1024);
        assert_eq!(snapshot.bytes_sent, 512);
        
        metrics.connection_closed();
        let snapshot2 = metrics.get_snapshot();
        assert_eq!(snapshot2.active_connections, 0);
    }
    
    #[test]
    fn test_system_metrics() {
        let metrics = SystemMetrics::new();

        // 等待一小段时间确保uptime > 0
        std::thread::sleep(Duration::from_millis(1));

        metrics.update_memory_usage(1024 * 1024);
        metrics.update_cpu_usage(50.5);

        let snapshot = metrics.get_snapshot();
        assert_eq!(snapshot.memory_usage, 1024 * 1024);
        assert_eq!(snapshot.cpu_usage, 50.5);
        assert!(snapshot.uptime.as_millis() > 0);
    }
}

impl PerformanceTuner {
    /// 创建新的性能调优器
    pub fn new() -> Self {
        Self {
            config: TuningConfig::default(),
            performance_history: Vec::new(),
            recommendations: Vec::new(),
        }
    }

    /// 创建带配置的性能调优器
    pub fn with_config(config: TuningConfig) -> Self {
        Self {
            config,
            performance_history: Vec::new(),
            recommendations: Vec::new(),
        }
    }

    /// 添加性能快照
    pub fn add_snapshot(&mut self, snapshot: PerformanceSnapshot) {
        self.performance_history.push(snapshot);

        // 保持历史记录数量限制
        if self.performance_history.len() > self.config.history_retention_count {
            self.performance_history.remove(0);
        }
    }

    /// 分析性能并生成建议
    pub fn analyze_and_recommend(&mut self, snapshot: &PerformanceSnapshot) -> Vec<TuningRecommendation> {
        self.add_snapshot(snapshot.clone());
        self.recommendations.clear();

        // 分析查询性能
        self.analyze_query_performance(snapshot);

        // 分析内存使用
        self.analyze_memory_usage(snapshot);

        // 分析缓存性能
        self.analyze_cache_performance(snapshot);

        // 分析CPU使用
        self.analyze_cpu_usage(snapshot);

        // 按优先级排序
        self.recommendations.sort_by(|a, b| b.priority.cmp(&a.priority));

        self.recommendations.clone()
    }

    /// 分析查询性能
    fn analyze_query_performance(&mut self, snapshot: &PerformanceSnapshot) {
        let thresholds = &self.config.performance_thresholds;

        if snapshot.query_performance.avg_query_time_ms > thresholds.max_query_time_ms as f64 {
            self.recommendations.push(TuningRecommendation {
                recommendation_type: RecommendationType::QueryOptimization,
                description: format!(
                    "平均查询时间 {:.2}ms 超过阈值 {}ms，建议优化查询或添加索引",
                    snapshot.query_performance.avg_query_time_ms,
                    thresholds.max_query_time_ms
                ),
                priority: Priority::High,
                expected_impact: "减少查询响应时间，提升用户体验".to_string(),
            });
        }

        if snapshot.query_performance.slow_queries_count > 10 {
            self.recommendations.push(TuningRecommendation {
                recommendation_type: RecommendationType::QueryOptimization,
                description: format!(
                    "检测到 {} 个慢查询，建议分析查询计划并优化",
                    snapshot.query_performance.slow_queries_count
                ),
                priority: Priority::Medium,
                expected_impact: "减少慢查询数量，提升整体性能".to_string(),
            });
        }
    }

    /// 分析内存使用
    fn analyze_memory_usage(&mut self, snapshot: &PerformanceSnapshot) {
        let thresholds = &self.config.performance_thresholds;

        if snapshot.memory_usage.usage_percent > thresholds.max_memory_usage_percent {
            self.recommendations.push(TuningRecommendation {
                recommendation_type: RecommendationType::MemoryOptimization,
                description: format!(
                    "内存使用率 {:.1}% 超过阈值 {:.1}%，建议增加内存或优化内存使用",
                    snapshot.memory_usage.usage_percent,
                    thresholds.max_memory_usage_percent
                ),
                priority: Priority::High,
                expected_impact: "减少内存压力，避免性能下降".to_string(),
            });
        }
    }

    /// 分析缓存性能
    fn analyze_cache_performance(&mut self, snapshot: &PerformanceSnapshot) {
        let thresholds = &self.config.performance_thresholds;

        if snapshot.cache_performance.hit_rate < thresholds.min_cache_hit_rate {
            self.recommendations.push(TuningRecommendation {
                recommendation_type: RecommendationType::CacheOptimization,
                description: format!(
                    "缓存命中率 {:.1}% 低于阈值 {:.1}%，建议调整缓存策略或增加缓存大小",
                    snapshot.cache_performance.hit_rate * 100.0,
                    thresholds.min_cache_hit_rate * 100.0
                ),
                priority: Priority::Medium,
                expected_impact: "提高缓存命中率，减少磁盘I/O".to_string(),
            });
        }
    }

    /// 分析CPU使用
    fn analyze_cpu_usage(&mut self, snapshot: &PerformanceSnapshot) {
        let thresholds = &self.config.performance_thresholds;

        if snapshot.cpu_usage > thresholds.max_cpu_usage_percent {
            self.recommendations.push(TuningRecommendation {
                recommendation_type: RecommendationType::ConfigurationTuning,
                description: format!(
                    "CPU使用率 {:.1}% 超过阈值 {:.1}%，建议优化查询或增加CPU资源",
                    snapshot.cpu_usage,
                    thresholds.max_cpu_usage_percent
                ),
                priority: Priority::High,
                expected_impact: "减少CPU负载，提升系统响应性".to_string(),
            });
        }
    }

    /// 获取历史性能趋势
    pub fn get_performance_trend(&self) -> Option<PerformanceTrend> {
        if self.performance_history.len() < 2 {
            return None;
        }

        let recent = &self.performance_history[self.performance_history.len() - 1];
        let previous = &self.performance_history[self.performance_history.len() - 2];

        Some(PerformanceTrend {
            query_time_trend: recent.query_performance.avg_query_time_ms - previous.query_performance.avg_query_time_ms,
            memory_usage_trend: recent.memory_usage.usage_percent - previous.memory_usage.usage_percent,
            cache_hit_rate_trend: recent.cache_performance.hit_rate - previous.cache_performance.hit_rate,
            cpu_usage_trend: recent.cpu_usage - previous.cpu_usage,
        })
    }

    /// 获取配置
    pub fn get_config(&self) -> &TuningConfig {
        &self.config
    }

    /// 更新配置
    pub fn update_config(&mut self, config: TuningConfig) {
        self.config = config;
    }
}

/// 性能趋势
#[derive(Debug, Clone)]
pub struct PerformanceTrend {
    /// 查询时间趋势（毫秒变化）
    pub query_time_trend: f64,
    /// 内存使用趋势（百分比变化）
    pub memory_usage_trend: f64,
    /// 缓存命中率趋势（比率变化）
    pub cache_hit_rate_trend: f64,
    /// CPU使用趋势（百分比变化）
    pub cpu_usage_trend: f64,
}

impl Default for TuningConfig {
    fn default() -> Self {
        Self {
            auto_tuning_enabled: true,
            monitoring_interval: 60, // 1分钟
            history_retention_count: 100,
            performance_thresholds: PerformanceThresholds::default(),
        }
    }
}

impl Default for PerformanceThresholds {
    fn default() -> Self {
        Self {
            max_query_time_ms: 1000, // 1秒
            max_memory_usage_percent: 80.0, // 80%
            max_cpu_usage_percent: 80.0, // 80%
            min_cache_hit_rate: 0.8, // 80%
        }
    }
}

#[cfg(test)]
mod performance_tests {
    use super::*;

    #[test]
    fn test_performance_tuner_creation() {
        let tuner = PerformanceTuner::new();
        assert!(tuner.config.auto_tuning_enabled);
        assert_eq!(tuner.config.monitoring_interval, 60);
        assert_eq!(tuner.performance_history.len(), 0);
        assert_eq!(tuner.recommendations.len(), 0);
    }

    #[test]
    fn test_performance_snapshot_analysis() {
        let mut tuner = PerformanceTuner::new();

        // 创建一个性能快照，查询时间超过阈值
        let snapshot = PerformanceSnapshot {
            timestamp: std::time::SystemTime::now(),
            query_performance: QueryPerformance {
                avg_query_time_ms: 1500.0, // 超过1000ms阈值
                max_query_time_ms: 2000,
                queries_per_second: 100.0,
                slow_queries_count: 15, // 超过10个慢查询
            },
            memory_usage: MemoryUsage {
                total_memory_bytes: 1024 * 1024 * 1024, // 1GB
                used_memory_bytes: 900 * 1024 * 1024,   // 900MB (87.5%)
                usage_percent: 87.5, // 超过80%阈值
            },
            cpu_usage: 85.0, // 超过80%阈值
            cache_performance: CachePerformance {
                cache_hits: 70,
                cache_misses: 30,
                hit_rate: 0.7, // 低于80%阈值
            },
        };

        let recommendations = tuner.analyze_and_recommend(&snapshot);

        // 应该生成多个建议
        assert!(!recommendations.is_empty());

        // 检查是否包含查询优化建议
        let query_recommendations: Vec<_> = recommendations.iter()
            .filter(|r| matches!(r.recommendation_type, RecommendationType::QueryOptimization))
            .collect();
        assert!(!query_recommendations.is_empty());

        // 检查是否包含内存优化建议
        let memory_recommendations: Vec<_> = recommendations.iter()
            .filter(|r| matches!(r.recommendation_type, RecommendationType::MemoryOptimization))
            .collect();
        assert!(!memory_recommendations.is_empty());

        // 检查是否包含缓存优化建议
        let cache_recommendations: Vec<_> = recommendations.iter()
            .filter(|r| matches!(r.recommendation_type, RecommendationType::CacheOptimization))
            .collect();
        assert!(!cache_recommendations.is_empty());
    }

    #[test]
    fn test_performance_trend_calculation() {
        let mut tuner = PerformanceTuner::new();

        // 添加第一个快照
        let snapshot1 = PerformanceSnapshot {
            timestamp: std::time::SystemTime::now(),
            query_performance: QueryPerformance {
                avg_query_time_ms: 100.0,
                max_query_time_ms: 200,
                queries_per_second: 50.0,
                slow_queries_count: 5,
            },
            memory_usage: MemoryUsage {
                total_memory_bytes: 1024 * 1024 * 1024,
                used_memory_bytes: 512 * 1024 * 1024,
                usage_percent: 50.0,
            },
            cpu_usage: 30.0,
            cache_performance: CachePerformance {
                cache_hits: 80,
                cache_misses: 20,
                hit_rate: 0.8,
            },
        };

        tuner.add_snapshot(snapshot1);

        // 添加第二个快照（性能下降）
        let snapshot2 = PerformanceSnapshot {
            timestamp: std::time::SystemTime::now(),
            query_performance: QueryPerformance {
                avg_query_time_ms: 150.0, // 增加50ms
                max_query_time_ms: 300,
                queries_per_second: 45.0,
                slow_queries_count: 8,
            },
            memory_usage: MemoryUsage {
                total_memory_bytes: 1024 * 1024 * 1024,
                used_memory_bytes: 600 * 1024 * 1024,
                usage_percent: 58.6, // 增加8.6%
            },
            cpu_usage: 40.0, // 增加10%
            cache_performance: CachePerformance {
                cache_hits: 75,
                cache_misses: 25,
                hit_rate: 0.75, // 下降0.05
            },
        };

        tuner.add_snapshot(snapshot2);

        let trend = tuner.get_performance_trend().unwrap();
        assert_eq!(trend.query_time_trend, 50.0);
        assert!((trend.memory_usage_trend - 8.6).abs() < 0.1);
        assert_eq!(trend.cpu_usage_trend, 10.0);
        assert!((trend.cache_hit_rate_trend + 0.05).abs() < 0.01);
    }

    #[test]
    fn test_tuning_config() {
        let config = TuningConfig::default();
        assert!(config.auto_tuning_enabled);
        assert_eq!(config.monitoring_interval, 60);
        assert_eq!(config.history_retention_count, 100);

        let thresholds = config.performance_thresholds;
        assert_eq!(thresholds.max_query_time_ms, 1000);
        assert_eq!(thresholds.max_memory_usage_percent, 80.0);
        assert_eq!(thresholds.max_cpu_usage_percent, 80.0);
        assert_eq!(thresholds.min_cache_hit_rate, 0.8);
    }

    #[test]
    fn test_metrics_collector_performance_analysis() {
        let collector = MetricsCollector::new();

        // 模拟一些指标数据
        collector.query_metrics.record_query_execution(Duration::from_millis(500));
        collector.storage_metrics.record_cache_hit();
        collector.storage_metrics.record_cache_miss();

        let recommendations = collector.analyze_performance();

        // 应该能够生成建议（即使是空的）
        assert!(recommendations.len() >= 0);
    }

    #[test]
    fn test_priority_ordering() {
        let mut recommendations = vec![
            TuningRecommendation {
                recommendation_type: RecommendationType::QueryOptimization,
                description: "Low priority".to_string(),
                priority: Priority::Low,
                expected_impact: "Minor".to_string(),
            },
            TuningRecommendation {
                recommendation_type: RecommendationType::MemoryOptimization,
                description: "Critical priority".to_string(),
                priority: Priority::Critical,
                expected_impact: "Major".to_string(),
            },
            TuningRecommendation {
                recommendation_type: RecommendationType::CacheOptimization,
                description: "Medium priority".to_string(),
                priority: Priority::Medium,
                expected_impact: "Moderate".to_string(),
            },
        ];

        recommendations.sort_by(|a, b| b.priority.cmp(&a.priority));

        assert_eq!(recommendations[0].priority, Priority::Critical);
        assert_eq!(recommendations[1].priority, Priority::Medium);
        assert_eq!(recommendations[2].priority, Priority::Low);
    }
}
